package village.rainbow.dailyscene.database;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import village.rainbow.dailyscene.Global;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * DB helper class
 * @author Kwon
 *
 */
public class SqlMapClient extends SQLiteOpenHelper{
	
	private Context _context;
	private static SqlMapClient _this;
	
	public static SqlMapClient getSqlMapInstance(Context context){
		if(_this == null)
			_this = new SqlMapClient(context);
		return _this;
	}
	
	public SqlMapClient(Context context) {
		super(context, Global.DB_NAME, null, Global.DB_VERSION);
		_context = context;
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
	}
	
	public void initDatabase(){
		if(!checkDatabase()){
			try {
				copyDatabase();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	

	public boolean checkDatabase(){
		FileInputStream fis =  null;
		try{
			String dbPath = _context.getDatabasePath(Global.DB_NAME).getCanonicalPath();
			fis = new FileInputStream(dbPath);	
		}catch(Exception e){
			e.printStackTrace();
		}
		return fis == null ? false : true;
	}
	
	private void copyDatabase() throws IOException{
		InputStream is = _context.getAssets().open(Global.DB_PATH);
		String dbPath = _context.getDatabasePath(Global.DB_NAME).getCanonicalPath();
		int findPos = dbPath.lastIndexOf("/");
		if (findPos != -1 && findPos < dbPath.length() - 1)
			dbPath = dbPath.substring(0, dbPath.lastIndexOf("/") + 1);
		File dir = new File(dbPath);
		if(!dir.exists())
			dir.mkdirs();
		
		File dbFile = new File(dir, Global.DB_NAME);
		FileOutputStream fous = new FileOutputStream(dbFile);
		byte[] buffer = new byte[2048];
		int length;
		while((length = is.read(buffer)) != -1){
			fous.write(buffer, 0, length);
		}
		fous.flush();
		fous.close();
		is.close();
	}
	
}